<?php

namespace app\api\controller;
use app\api\model\Account;
class Base
{

    //注册功能
    public function register($memberId, $memberName, $memberPassword)
    {
        //传入学号，姓名，密码注册
        //规则1：学号唯一
        //规则2：密码md5加密
        $hasAcct = Account::where('member_id', $memberId)->find();
        if ($hasAcct) {
            output_error("学号重复");
        }
        $pwdMd5 = md5($memberPassword);
        $acct = Account::create([
            'member_id' => $memberId,
            'member_name' => $memberName,
            'member_password' => $pwdMd5]);
        if ($acct) {
            output_data("注册成功");
        } else {
            output_error("注册失败");
        }
    }

    //找回密码
    public function findpass($memberId, $memberPassword)
    {
        //通过学号，姓名重置密码
        //规则1：密码md5加密
        $acct = Account::where('member_id', $memberId)->find();
        if (!$acct) {
            output_error("学号不存在");
        }
        $newPwdMd5 = md5($memberPassword);
        $res = Account::where('member_id', $memberId)->update(['member_password' => $newPwdMd5]);
        if (!$res && $acct->member_password != $newPwdMd5) {
            output_error("重置密码失败，请重试");
        }
        output_data("重置密码成功");
    }

    //登录功能
    public function login($memberId, $memberPassword)
    {
        //通过学号，密码登录，返回Token
        //规则1：token由学号+当前时间戳md5加密生成
        $pwdMd5 = md5($memberPassword);//校验加密后的密码
        $acct = Account::where('member_id', $memberId)
            ->where('member_password', $pwdMd5)
            ->find();
        if (!$acct) {
            output_error("学号或密码错误");
        }
        $token = md5($memberId + time());
        $acct->member_token = $token;
        $acct->save();//保存token
        return $token;
    }

}
